package data.connector.rippling.api;

import com.fasterxml.jackson.databind.JsonNode;
import data.connector.rippling.api.base.BaseApiService;
import data.connector.rippling.api.base.ResultMessageModel;
import data.connector.rippling.config.RabbitConfiguration;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author Jay Yang
 */

@Log4j2
@Service
public class LeaveRequestsService extends BaseApiService {

    public void asyncLeaveRequests(Integer tenant) {
        this.initParams(tenant)
                .flatMapMany(params -> this.forwardOnlyClient.getRepository("/api/platform/api/leave_requests", params))
                .subscribe(result -> {
                    if (result.rawStatusCode() == super.SUCCESS_CODE) {
                        result.bodyToFlux(JsonNode.class).subscribe(jsonNode ->
                                this.messagingTemplate.convertAndSend(RabbitConfiguration.DATA_CONNECTOR_RIPPLING,
                                        "rippling-leave_requests-key",
                                        ResultMessageModel.builder().action(ResultMessageModel.MessageModelAction.ADD)
                                                .type(ResultMessageModel.MessageModelType.LEAVE_REQUESTS)
                                                .sendTime(LocalDateTime.now())
                                                .entity(jsonNode)
                                                .tenantId(tenant)
                                                .build()));
                    } else {
                        super.setExceptionLog(tenant, result, "/api/platform/api/leave_requests");
                    }
                });
    }


}
